/* 引入router */
import router from './router'
/* 引入store */
import store from './store'
/*  引入Message函数(elementui的提示函数)*/
import {Message} from 'element-ui'
/* 引入进度条 */
import NProgress from 'nprogress'
/* 引入getPageTitle用于获取页面标题的函数 */
import getPageTitle from '@/utils/get-page-title'
/* 引入getToken函数用于获取cookie中的token字段 */
import {getToken} from '@/utils/auth'

/*白名单页面数组(不需要登录就能访问的页面)*/
const whitePageList = ['/login', '/404']

/* 全局前置路由守位(路由跳转之前执行) */
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      Message.warning('已经登录')
      next(false)
      NProgress.done()
    } else {
      const userId = store.getters.userId
      if (userId) {
        next()
      } else {
        try {
          const {roles} = await store.dispatch('user/getUserInfoAction')
          // 派发action过滤出最终路由，返回最终路由
          const resultRoutes = await store.dispatch('menuStore/addRoutesAction', roles.menus)
          // 添加最终路由到路由系统(404路由必须在最后)
          router.addRoutes([...resultRoutes, {path: '*', redirect: '/404', hidden: true}])
          next({...to, replace: true})
        } catch (e) {
          Message.warning('登录过期')
          await store.dispatch('user/logoutAction')
          next({path: '/login', query: {redirect: to.fullPath}})
          NProgress.done()
        }
      }
    }
  } else {
    if (whitePageList.indexOf(to.path) !== -1) {
      next()
    } else {
      Message.warning('请先登录')
      next({path: '/login', query: {redirect: to.fullPath}})
      NProgress.done()
    }
  }
})

/* 全局后置路由守位(路由跳转之后执行) */
router.afterEach((to, from) => {
  NProgress.done()
  document.title = getPageTitle(to.meta.title)
})
